<?php

namespace app\merchant\job;

use app\common\controller\ActionLogs;
use app\common\model\Agent;
use app\common\model\CardBizPutLog;
use app\common\model\CardBizPutLogMember;
use app\common\model\CardGeneral;
use app\common\model\CardGivecardLog;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\WxOpen;
use think\Db;
use think\Queue;
use think\queue\Job;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;
use think\Session;
class Sendbizput
{

    public function fire(Job $job, $data)
    {
        $CardBizPutLogMember = new CardBizPutLogMember();
        $sql['id'] = $data['cardlogmember_id'];
        $startres = $this->startcardus($data['data']);
        if ($startres['errcode'] == 0) {
            $restat['ks_info'] = json_encode($startres);
            $CardBizPutLogMember->allowField(true)->save($restat, $sql);
            $isJobDone = $this->task_biz_put($data);

            $job->delete();

            if ($isJobDone) {
                $restat['js_info'] = $this->endcardus($data['param']['card_id']);
                $CardBizPutLogMember->allowField(true)->save($restat, $sql);
                //如果任务执行成功， 记得删除任务
                $job->delete();
                return $isJobDone;
            } else {
                if ($job->attempts() > 3) {
                    $restat['js_info'] = $this->endcardus($data['param']['card_id']);
                    $CardBizPutLogMember->allowField(true)->save($restat, $sql);
                    //通过这个方法可以检查这个任务已经重试了几次了
                    print("<warn>任务已完成3次!" . "</warn>\n");
                    $job->delete();
                    // 也可以重新发布这个任务
                    //print("<info>Hello Jobmach will be availabe again after 2s."."</info>\n");
                    //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
                }
            }
        }else{
            $restat['ks_info'] = json_encode($startres);
            $CardBizPutLogMember->allowField(true)->save($restat, $sql);
            $job->delete();
        }
    }



    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     *
     * param: card_id   userlist  top_mid  add_bonus  action_user
     * bizinfo: card_id_list id c_id_list
     *
     */
    //批量执行跟随推荐(积分
    public function task_biz_put($param)
    {
            //初始化微信类
            if (isset($param['param']['card_id'])) {
                $option = $this->options($param['param']['card_id']);
                $CardBizPurLog = new CardBizPutLog();
                $userlist = $param['param']['userlist'];
                foreach ($userlist as $k => $v) {
                    $datas['code'] = $v['code'];
                    $datas['biz_action_id'] = $param['biz_action_id'];
                    $datas['openid'] = $v['openid'];
                    $datas['card_id'] = $param['param']['card_id'];
                    $datas['card_id_list'] = $param['bizinfo']['card_id_list'];
                    $datas['give_rec_id'] = $param['bizinfo']['id'];
                    $datas['top_mid'] = $param['param']['top_mid'];
                    $datas['mid'] = $v['mid'];
                    $recs = $this->rec_giveuserlog($datas);
                    if ($recs !== 0) {
                        $datass[$k]['code'] = $v['code'];
                        $datass[$k]['card_id'] = $param['param']['card_id'];
                        $datass[$k]['add_bonus'] = $param['param']['add_bonus'];
                        $datass[$k]['top_mid'] = $param['param']['top_mid'];
                        $datass[$k]['card_id_list'] = $param['bizinfo']['card_id_list'];
                        $datass[$k]['give_rec_id'] = $param['bizinfo']['id'];
                        $datass[$k]['mid'] = $v['mid'];
                        $datass[$k]['c_id'] = $v['c_id'];
                        $datass[$k]['us_c_id'] = $v['id'];
                        $datass[$k]['openid'] = $v['openid'];
                        $datass[$k]['biz_id'] = $param['bizinfo']['id'];
                        $datass[$k]['c_id_list'] = $param['bizinfo']['c_id_list'];
                        //END
                        $option['card_id'] = $param['param']['card_id'];
                        $option['code'] = $v['code'];
                        $option['orderid'] = '';
                        $option['num'] = $param['param']['add_bonus'];
                        $option['bd_cate'] = 'bonus';
                        $option['type'] = 1;//变动 1增加 2减少
                        $option['cate'] = 1;  //变动类型
                        $option['pay_cate'] = 4; //支付方式
                        $option['source'] = 'web';  //来源
                        $option['remark'] = '发券赠送'; //备注
                        $option['action_user'] = $param['param']['action_user'];//操作人
                        $Fztest = new WnCardObj($option);
                        $res = $Fztest->init();
                        $datass[$k]['info'] = json_encode($res,JSON_UNESCAPED_UNICODE);
                    }
                }
                $CardBizPurLog->allowField(true)->saveAll($datass);
                return 'success';
            }
    }

    //更新会员卡状态为结束跟随推荐
    private function startcardus($data){
        $option = $this->options($data['card_id']);
        $WxObj = new Wxobjopen($option);
        $res = $WxObj->updateUserCard($data);
        return $res;
//        $ActionLogs = new ActionLogs();
//        $ActionLogs-> writelog("payos","sendbiz","send/bizend","关闭跟随推荐:",$res);
    }

    //更新会员卡状态为结束跟随推荐
    private function endcardus($card_id){
        $datas['card_id'] = $card_id;
        $datas['member_card']['modify_msg_operation']['url_cell']['card_id_list'] = [];
        $datas['member_card']['modify_msg_operation']['url_cell']['end_time'] = time();
        $datas['member_card']['modify_msg_operation']['url_cell']['text'] = '';
        $datas['member_card']['modify_msg_operation']['url_cell']['url'] = '';
        $option = $this->options($card_id);
        $WxObj = new Wxobjopen($option);
        $res = $WxObj->updateUserCard($datas);
        return $res;
//        $ActionLogs = new ActionLogs();
//        $ActionLogs-> writelog("payos","sendbiz","send/bizend","关闭跟随推荐:",$res);
    }

    private function rec_giveuserlog($arr){
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['card_id_list'];
        if ($zs_card_id){
            $zs_card_id = json_decode($arr['card_id_list'],true);
            $data = [];
            foreach ($zs_card_id as $k => $v) {
                $data[$k]['biz_action_id'] = $arr['biz_action_id'];
                $data[$k]['card_id'] = $arr['card_id'];
                $data[$k]['openid'] = $arr['openid'];
                $data[$k]['code'] = $arr['code'];
                $data[$k]['put_type'] = 'bizbonus_card';
                $data[$k]['zs_card_id'] = $v['zs_card_id'];
                $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                $data[$k]['mid'] = $arr['mid'];
                $data[$k]['top_mid'] = $arr['top_mid'];
                $data[$k]['put_sume'] = $v['zs_no'];
                $data[$k]['create_time'] = time();
            }
            $res = $CardGivecardLog->allowField(true)->saveAll($data);
        }else{
            $res = 0;
        }
        return $res;

    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    public function options2($gh_id)
    {
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mab['gh_id'] = $gh_id;
        $users = $WxOpen->where($mab)->find();
        $Merchant=new Merchant();
        $users2=$Merchant->where(array('wx_open_id' => $users['id']))->value('agent');
        $config = $Agent->where(array('id' =>$users2))->field('component_token,component_encodingaeskey,component_appid,component_appsecret,open_ticket')->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}
